package main;

import java.util.Stack;

/**
 * Provides a set of methods that you can use to measure the time. *
 * ThreadUnsafe.
 */
public class TimeTest {

	private static Stack<Stopwatch> stack = new Stack<Stopwatch>();

	/**
	 * Enables or disables time test.
	 */
	public static boolean isEnabled;

	/**
	 * Starts measuring elapsed time for an interval.
	 * 
	 * @param message
	 *            message that should be shown.
	 */
	public static void start(String message) {
		if (isEnabled) {
			Stopwatch watch = new Stopwatch(message);
			stack.push(watch);
		}
	}

	/**
	 * Stops measuring elapsed time for an interval and outputs a message.
	 */
	public static void stop() {
		if (isEnabled) {
			Stopwatch watch = stack.pop();
			watch.stop();
		}
	}

	/**
	 * Provides a set of methods that you can use to measure the time.
	 * 
	 */
	private static class Stopwatch {

		/**
		 * Initializes a new instance of the Stopwatch class.
		 * 
		 * @param message
		 *            message that should be shown.
		 */
		public Stopwatch(String message) {
			this.message = message;
			start();
		}

		private long startTime = 0;
		private long stopTime = 0;
		private boolean running = false;
		private String message;

		/**
		 * Starts measuring elapsed time for an interval.
		 */
		public void start() {
			this.startTime = System.currentTimeMillis();
			this.running = true;
		}

		/**
		 * Stops measuring elapsed time for an interval and outputs a message.
		 */
		public void stop() {
			this.stopTime = System.currentTimeMillis();
			this.running = false;
			Console.printlnWithForce("------ " + message + " (duration:"
					+ getElapsedTime() + " ms)");
		}

		/**
		 * elapsed time in milliseconds
		 * 
		 * @return elapsed time in milliseconds
		 */
		public long getElapsedTime() {
			long elapsed;
			if (running) {
				elapsed = (System.currentTimeMillis() - startTime);
			} else {
				elapsed = (stopTime - startTime);
			}
			return elapsed;
		}

		/**
		 * Elapsed time in seconds
		 * 
		 * @return Elapsed time in seconds
		 */
		@SuppressWarnings("unused")
		public long getElapsedTimeSecs() {
			long elapsed;
			if (running) {
				elapsed = ((System.currentTimeMillis() - startTime) / 1000);
			} else {
				elapsed = ((stopTime - startTime) / 1000);
			}
			return elapsed;
		}
	}
}
